﻿using System.ServiceModel.Channels;

namespace Kobets.Automation.Chimera.Common
{
    /// <summary>
    /// CustomHttpBinding is used for WCF communication between Agent and Controller
    /// The reason for creating it was to be able to set MaxMessageSize and HTTPS use with more flexibility
    /// </summary>
    public class CustomHttpBinding : CustomBinding
    {
        private readonly bool _useHttps;
        private readonly HttpTransportBindingElement _transport;

        public CustomHttpBinding(bool useHttps)
        {
            _useHttps = useHttps;
            _transport = useHttps ? new HttpsTransportBindingElement() : new HttpTransportBindingElement();
        }

        public long MaxMessageSize
        {
            set
            {
                _transport.MaxReceivedMessageSize = value;
                _transport.MaxBufferSize = (int)value;
            }
        }

        public override BindingElementCollection CreateBindingElements()
        {
            BindingElement security = _useHttps ? SecurityBindingElement.CreateSecureConversationBindingElement(SecurityBindingElement.CreateUserNameOverTransportBindingElement()) : SecurityBindingElement.CreateSecureConversationBindingElement(SecurityBindingElement.CreateUserNameForSslBindingElement(true));

            var encoding = new BinaryMessageEncodingBindingElement { ReaderQuotas = { MaxArrayLength = int.MaxValue }};

            return new BindingElementCollection(new[]
            {
                security,
                encoding,
                _transport
            });
        }
    }

}
